import pandas as pd
import openpyxl
import xlrd
import chardet
import os
import warnings

warnings.filterwarnings('ignore')

pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', 100)
pd.set_option('display.width', 1000)


def _analyze_dataframe_details(df: pd.DataFrame, file_path: str, sheet_name: str = None, detected_encoding: str = None,
                               read_engine: str = None):
    print(
        "\n" + "=" * 30 + f" 数据分析结果 ({os.path.basename(file_path)}{f' - Sheet: {sheet_name}' if sheet_name else ''}) " + "=" * 30)

    if detected_encoding:
        print(f"文件编码 (实际使用): {detected_encoding}")
    if read_engine:
        print(f"读取引擎 (推测或使用): {read_engine}")
    if sheet_name:
        print(f"工作表名称: {sheet_name}")

    print("\n[DataFrame Head]")
    print(df.head())

    print("\n[DataFrame Info]")
    df.info()

    print("\n[DataFrame Columns]")
    all_columns_list = df.columns.to_list()
    print(all_columns_list)

    print("\n[DataFrame Describe]")
    print(df.describe(include='all'))

    print("\n" + "=" * 30 + " 分析结束 " + "=" * 30)


def read_and_analyze_file(file_path: str):
    if not os.path.exists(file_path):
        print(f"错误：文件未找到 - {file_path}")
        return None

    file_extension = os.path.splitext(file_path)[1].lower()

    print(f"开始处理文件: {file_path}")

    if file_extension == '.csv':
        print("文件类型: CSV")
        df = None
        detected_encoding = None
        try:
            with open(file_path, 'rb') as f:
                rawdata = f.read(20000)
            result = chardet.detect(rawdata)
            initial_encoding = result['encoding']
            confidence = result['confidence']
            print(f"Chardet检测到的编码: {initial_encoding} (置信度: {confidence:.2f})")
            if initial_encoding is None:
                print("Chardet未能明确检测到编码，将尝试常用编码。")
        except Exception as e:
            print(f"使用Chardet检测编码时出错: {e}")
            initial_encoding = None

        encodings_to_try = []
        if initial_encoding and initial_encoding.lower() not in ['ascii']:
            encodings_to_try.append(initial_encoding)
        for enc in ['utf-8', 'gbk', 'gb18030', 'utf-8-sig', 'latin1']:
            if enc not in encodings_to_try:
                encodings_to_try.append(enc)

        print(f"尝试读取编码列表: {encodings_to_try}")

        for encoding in encodings_to_try:
            try:
                print(f"尝试使用编码 '{encoding}' 读取CSV...")
                df = pd.read_csv(file_path, encoding=encoding)
                detected_encoding = encoding
                print(f"成功使用编码 '{encoding}' 读取CSV.")
                break
            except UnicodeDecodeError:
                print(f"使用编码 '{encoding}' 失败 (UnicodeDecodeError)。")
            except Exception as e:
                print(f"使用编码 '{encoding}' 读取时发生其他错误: {e}")

        if df is None:
            print("尝试多种编码后仍无法读取CSV文件。")
            return None

        _analyze_dataframe_details(df, file_path, detected_encoding=detected_encoding)
        return df

    elif file_extension in ['.xlsx', '.xls']:
        print(f"文件类型: Excel ({file_extension})")
        dfs_dict = None
        read_engine = None

        try:
            if file_extension == '.xlsx':
                read_engine = 'openpyxl'
                print(f"尝试使用推测引擎: {read_engine} 读取所有工作表...")
                dfs_dict = pd.read_excel(file_path, engine=read_engine, sheet_name=None)
            elif file_extension == '.xls':
                read_engine = 'xlrd'
                print(f"尝试使用推测引擎: {read_engine} 读取所有工作表...")
                dfs_dict = pd.read_excel(file_path, engine=read_engine, sheet_name=None)

            if dfs_dict:
                print(f"成功读取Excel文件。使用的引擎 (推测): {read_engine}")

        except ImportError as e:
            print(f"读取Excel失败: 缺少必要的库。请确保已安装 'openpyxl' (用于.xlsx) 或 'xlrd' (用于.xls)。错误: {e}")
            return None
        except Exception as e:
            print(f"使用指定引擎读取Excel文件失败: {e}")
            dfs_dict = None  # 重置以便尝试自动引擎

        if dfs_dict is None:
            try:
                print("尝试让pandas自动选择引擎读取所有工作表...")
                dfs_dict = pd.read_excel(file_path, sheet_name=None)
                read_engine = "pandas-auto"
                print("成功使用pandas自动引擎选择读取Excel文件。")
            except Exception as e_auto:
                print(f"使用pandas自动引擎选择也失败了: {e_auto}")
                return None

        if dfs_dict:
            if not isinstance(dfs_dict, dict):  # 如果只有一个sheet，某些pandas版本可能直接返回DataFrame
                temp_df = dfs_dict
                dfs_dict = {'Sheet1': temp_df}  # 假设默认名称，或从ExcelFile获取
                if hasattr(pd.ExcelFile(file_path), 'sheet_names') and pd.ExcelFile(file_path).sheet_names:
                    dfs_dict = {pd.ExcelFile(file_path).sheet_names[0]: temp_df}

            print(f"\nExcel文件包含 {len(dfs_dict)} 个工作表: {list(dfs_dict.keys())}")
            for sheet_name, df_sheet in dfs_dict.items():
                _analyze_dataframe_details(df_sheet, file_path, sheet_name=sheet_name, read_engine=read_engine)
            return dfs_dict
        else:
            print("未能成功加载任何工作表从Excel文件。")
            return None

    else:
        print(f"错误：不支持的文件类型 '{file_extension}'。请提供CSV或Excel (.xls, .xlsx) 文件。")
        return None


if __name__ == "__main__":
    df1 = read_and_analyze_file(r'iris_test.csv')



